package com.apps.helper;

import com.apps.sexctption.NullException;
import com.apps.sutils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 页面管理,主要用于实现跳回上一页
 */
public class PageConextHelper
{

    /**
     * 当前页面
     */
    public static final String CURRENT_PAGE_KEY="curr_page";
    /**
     * 上一个页面
     */
    public static final String HISTORY_PAGE_KEY="his_page";
    /**
     * 能加进历史页面的前缀
     */
    public static final String[] HISTORY_PAGE_Patterns={"/page/**"};
    /**
     * 静态资源路径,静态资源不能被视为路径
     */
    private static final String[] checkIsStaticPathPatterns={"/static/**","/webjars/**"};

    /**
     * 获取当前页面路径
     * @return 如果没有登录返回null
     */
    public static String getCurrentPage()
    {

        HttpSession sessonContext = ThreadContextHelper.getSession();
        if (sessonContext != null) {
            try {
                return  (String) sessonContext.getAttribute(PageConextHelper.CURRENT_PAGE_KEY);
            } catch (IllegalStateException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取上一个页面的路径
     * @return
     */
    public static String getHistoryPage()
    {

        HttpSession sessonContext = ThreadContextHelper.getSession();
        if(null == sessonContext)
            throw new NullException("session为空");
        try {
                  String result= (String) sessonContext.getAttribute(PageConextHelper.HISTORY_PAGE_KEY);
                  if(null == result)
                      result= "/";
                  return result;
            } catch (IllegalStateException e) {
                return null;
            }
    }

    /**
     * 设置当前线程的页面路径
     * @param request
     */
    public static void SetRequest(HttpServletRequest request)
    {
        //如果是静态资源则直接返回
        if(StringUtils.isContains(checkIsStaticPathPatterns,request.getRequestURI()))
            return;
        HttpSession sessonContext = ThreadContextHelper.getSession();
        if(null == sessonContext)
            throw new NullException("session为空");
        //设置当前页面
        sessonContext.setAttribute(PageConextHelper.CURRENT_PAGE_KEY,request.getRequestURI());
        //设置历史页面
        if(StringUtils.isContains(HISTORY_PAGE_Patterns,request.getRequestURI()))
            sessonContext.setAttribute(PageConextHelper.HISTORY_PAGE_KEY,request.getRequestURI());
    }

}
